#region

using System;
using System.Collections.Generic;
using SFML.Graphics;
using SFMLStart.Data;
using SFMLStart.Utilities;
using VeeTileEngine2012;

#endregion

namespace TimeDRODPOF.TDComponents
{
    public class TDCSwitch : Component
    {
        public Action OnTurnOff;
        public Action OnTurnOn;
        private IntRect? _offTextureRect;
        private IntRect? _onTextureRect;

        public TDCSwitch(bool mIsOff = false)
        {
            IsOff = mIsOff;
            OnlyOnTags = new List<string>();
            OnlyOffTags = new List<string>();
        }

        public bool IsOff { get; set; }
        public string OffTextureName { get; set; }
        public string OnTextureName { get; set; }
        public IntRect? OffTextureRect { get { return _offTextureRect; } set { _offTextureRect = value; } }
        public IntRect? OnTextureRect { get { return _onTextureRect; } set { _onTextureRect = value; } }
        public List<string> OnlyOnTags { get; set; }
        public List<string> OnlyOffTags { get; set; }

        public override void Added()
        {
            base.Added();

            if (IsOff) TurnOff();
            else TurnOn();
        }

        public void TurnOn()
        {
            IsOff = false;
            if (OnTextureName != null) Entity.GetComponent<TDCRender>().GetSprite(0).Texture = Assets.GetTexture(OnTextureName);
            if (OnTextureRect != null) Entity.GetComponent<TDCRender>().GetSprite(0).TextureRect = (IntRect) OnTextureRect;

            foreach (var tagToAdd in OnlyOnTags) Entity.AddTags(tagToAdd);
            foreach (var tagToRemove in OnlyOffTags) Entity.RemoveTags(tagToRemove);

            OnTurnOn.SafeInvoke();
        }

        public void TurnOff()
        {
            IsOff = true;
            if (OffTextureName != null) Entity.GetComponent<TDCRender>().GetSprite(0).Texture = Assets.GetTexture(OffTextureName);
            if (OffTextureRect != null) Entity.GetComponent<TDCRender>().GetSprite(0).TextureRect = (IntRect) OffTextureRect;

            foreach (var tagToAdd in OnlyOffTags) Entity.AddTags(tagToAdd);
            foreach (var tagToRemove in OnlyOnTags) Entity.RemoveTags(tagToRemove);

            OnTurnOff.SafeInvoke();
        }

        public void Toggle()
        {
            if (IsOff)
                TurnOn();
            else
                TurnOff();
        }
    }
}